package com.dsp.order.service.impl;

import com.dsp.order.dao.OrderDao;
import com.dsp.order.dto.OrderDTO;
import com.dsp.order.entity.Order;
import com.dsp.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.dromara.hmily.annotation.HmilyTCC;
import org.dromara.hmily.common.exception.HmilyRuntimeException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Resource
    private OrderDao orderDao;

    public List<Order> findAll(){
        return (List<Order>) orderDao.findAll();
    }

    @HmilyTCC(confirmMethod = "confirmMethod", cancelMethod = "cancelMethod")
    @Transactional(rollbackFor = Exception.class)
    @Override
    public OrderDTO create(OrderDTO orderDTO) {
        Order order = orderDao.findByName(orderDTO.getName());
        if(Objects.nonNull(order)){
            throw new HmilyRuntimeException("已有订单异常:"+orderDTO.getId());
        }
        order = new Order();
        order.setName(orderDTO.getName());
        order.setEnable(1);
        order.setPayStatus(0);
        order = orderDao.save(order);
        orderDTO.setId(order.getId());
        orderDTO.setName(order.getName());
        System.out.println("生成 "+orderDTO.getName()+" 的订单！！");
        return orderDTO;
    }

    @Transactional(rollbackFor = Exception.class)
    public OrderDTO confirmMethod(OrderDTO orderDTO) {
        Long id = orderDao.confirm(orderDTO.getName());
        if (null == id) {
            throw new HmilyRuntimeException("订单确认异常:"+orderDTO.getName());
        }
        orderDTO.setId(id);
        log.info("订单...确认:{}，id：{}",orderDTO.getName(),id);
        return orderDTO;
    }

    @Transactional(rollbackFor = Exception.class)
    public OrderDTO cancelMethod(OrderDTO orderDTO) {
        final int decrease = orderDao.cancel(orderDTO.getName());
        log.info("订单...恢复:{}，影响数据条数：{}",orderDTO.getName(),decrease);
        return orderDTO;
    }
}
